/**
 * UI管理类
 * 负责管理用户界面的渲染和交互
 */

export class UIManager {
    constructor(state) {
        this.state = state;
        this.events = {};
        this.currentFileView = 'main.c';
    }

    init() {
        this.render();
        this.bindEvents();
    }

    // 渲染应用
    render() {
        const app = document.getElementById('app');
        if (app) {
            // 由于UI已在HTML中定义，这里不需要重新渲染
            // 只需要确保事件绑定正确
        }
    }

    // 获取应用模板
    getAppTemplate() {
        return `
            <!-- 头部 -->
            <header class="text-center mb-12">
                <h1 class="text-4xl md:text-5xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-500 py-4">
                    <i class="fas fa-microchip mr-3"></i>ESP32 开发辅助工具
                </h1>
                <p class="text-gray-300 max-w-2xl mx-auto">
                    一站式ESP32项目初始化工具，从配置到代码生成，再到设备烧录，全流程支持
                </p>
            </header>

            <!-- 安全提示 -->
            <div class="bg-yellow-900 border-l-4 border-yellow-500 p-4 rounded mb-8">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-yellow-300">
                            <strong>重要安全提示：</strong>现代浏览器和操作系统可能会阻止下载的文件。
                            如果遇到此问题，请尝试以下方法：
                            <ol class="list-decimal pl-5 mt-2 space-y-1">
                                <li>点击下载后选择"保留"或"允许"</li>
                                <li>在下载管理器中恢复被阻止的文件</li>
                                <li>使用"导出为文本"备选方案</li>
                                <li>检查杀毒软件隔离区并恢复文件</li>
                            </ol>
                        </p>
                    </div>
                </div>
            </div>

            <!-- 主要功能区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- 左侧配置区域 -->
                <div class="space-y-8">
                    <!-- 项目配置区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-cog text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">项目配置</h2>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- 芯片型号选择 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-300 mb-2">芯片型号</label>
                                <select id="chip-selector" class="w-full bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                    <option value="ESP32-WROOM-32">ESP32-WROOM-32</option>
                                    <option value="ESP32-C3-MINI-1">ESP32-C3-MINI-1</option>
                                    <option value="ESP32-S3">ESP32-S3</option>
                                    <option value="ESP32-PICO">ESP32-PICO</option>
                                </select>
                            </div>
                            
                            <!-- 项目名称 -->
                            <div>
                                <label class="block text-sm font-medium text-gray-300 mb-2">项目名称</label>
                                <input type="text" id="project-name" value="esp32_project" class="w-full bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>
                            
                            <!-- 功能模块配置 -->
                            <div class="md:col-span-2">
                                <label class="block text-sm font-medium text-gray-300 mb-2">功能模块</label>
                                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="wifi-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="wifi-enable" class="ml-2 block text-sm">WiFi</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="bluetooth-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="bluetooth-enable" class="ml-2 block text-sm">蓝牙</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="http-server-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="http-server-enable" class="ml-2 block text-sm">HTTP服务器</label>
                                    </div>
                                    <div class="flex items-center bg-gray-700 rounded-lg p-3">
                                        <input type="checkbox" id="ota-enable" class="rounded bg-gray-600 border-gray-600 text-indigo-600 focus:ring-indigo-500">
                                        <label for="ota-enable" class="ml-2 block text-sm">OTA更新</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 可视化配置界面 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-microchip text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">引脚配置</h2>
                        </div>
                        <div id="pin-configuration" class="border-2 border-dashed border-gray-600 rounded-lg p-4 text-center min-h-[200px] flex items-center justify-center">
                            <p class="text-gray-400">选择芯片型号以加载引脚图</p>
                        </div>
                    </div>
                    
                    <!-- 项目文件管理区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-folder-tree text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">项目结构</h2>
                        </div>
                        <div id="file-structure" class="border border-gray-700 rounded-lg p-4 bg-gray-900 min-h-[150px]">
                            <p class="text-gray-400 text-center">生成代码后将显示项目文件结构</p>
                        </div>
                        <div class="mt-4 flex space-x-3">
                            <button id="download-zip" class="flex-1 bg-gradient-to-r from-green-500 to-emerald-600 text-white py-2 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                <i class="fas fa-download mr-2"></i>下载项目
                            </button>
                            <button id="export-text" class="flex-1 bg-gradient-to-r from-blue-500 to-cyan-600 text-white py-2 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                <i class="fas fa-copy mr-2"></i>复制结构
                            </button>
                        </div>
                        <div class="mt-3 text-xs text-gray-400">
                            <p><i class="fas fa-info-circle mr-1"></i>如果下载被阻止，可使用"导出为文本"功能</p>
                        </div>
                    </div>
                </div>
                
                <!-- 右侧代码和设备区域 -->
                <div class="space-y-8">
                    <!-- 代码生成区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500 h-full flex flex-col">
                        <div class="flex items-center justify-between mb-4">
                            <div class="flex items-center">
                                <i class="fas fa-code text-indigo-400 text-xl mr-3"></i>
                                <h2 class="text-xl font-semibold">代码预览</h2>
                            </div>
                            <button id="generate-code" class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white py-1 px-4 rounded-lg hover:opacity-90 transition text-sm flex items-center">
                                <i class="fas fa-bolt mr-2"></i>重新生成
                            </button>
                        </div>
                        <div class="flex space-x-2 mb-3 overflow-x-auto">
                            <button class="tab-btn active text-sm py-1 px-3 rounded bg-gray-700" data-file="main.c">main.c</button>
                            <button class="tab-btn text-sm py-1 px-3 rounded bg-gray-700" data-file="CMakeLists.txt">CMakeLists.txt</button>
                            <button class="tab-btn text-sm py-1 px-3 rounded bg-gray-700" data-file="sdkconfig">sdkconfig</button>
                        </div>
                        <div id="code-preview" class="flex-grow border border-gray-700 rounded-lg overflow-auto max-h-[400px] bg-gray-900">
                            <pre class="m-0 !bg-gray-900"><code class="language-c">/* 生成的代码将在此显示 */</code></pre>
                        </div>
                    </div>
                    
                    <!-- 设备交互区 -->
                    <div class="bg-gray-800 rounded-xl shadow-2xl p-6 border border-gray-700 transition-all hover:border-indigo-500">
                        <div class="flex items-center mb-4">
                            <i class="fas fa-plug text-indigo-400 text-xl mr-3"></i>
                            <h2 class="text-xl font-semibold">设备交互</h2>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="space-y-4">
                                <button id="connect-device" class="w-full bg-gradient-to-r from-blue-500 to-indigo-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                    <i class="fas fa-link mr-2"></i>连接设备
                                </button>
                                <div id="connection-status" class="text-center py-3 rounded-lg bg-gray-700 flex items-center justify-center">
                                    <span class="status-indicator status-disconnected mr-2"></span>
                                    <span>未连接设备</span>
                                </div>
                            </div>
                            <div class="space-y-4">
                                <input type="file" id="firmware-file" accept=".bin" class="hidden">
                                <button id="select-firmware" class="w-full bg-gradient-to-r from-purple-500 to-pink-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center">
                                    <i class="fas fa-file-import mr-2"></i>选择固件
                                </button>
                                <button id="flash-firmware" class="w-full bg-gradient-to-r from-red-500 to-orange-600 text-white py-3 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center" disabled>
                                    <i class="fas fa-burn mr-2"></i>烧录固件
                                </button>
                            </div>
                        </div>
                        <div class="mt-6">
                            <div class="flex justify-between mb-1">
                                <span class="text-sm font-medium">烧录进度</span>
                                <span id="progress-percent" class="text-sm font-medium">0%</span>
                            </div>
                            <div class="w-full bg-gray-700 rounded-full h-2.5">
                                <div id="flash-progress" class="bg-gradient-to-r from-green-400 to-emerald-500 h-2.5 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>
                        <div class="mt-4">
                            <label class="block text-sm font-medium text-gray-300 mb-2">串口监控</label>
                            <div id="serial-monitor" class="border border-gray-700 rounded-lg p-3 bg-gray-900 h-32 overflow-y-auto text-sm font-mono">
                                <p class="text-gray-400">设备连接后将显示串口信息...</p>
                            </div>
                            <div class="flex mt-2 space-x-2">
                                <input type="text" id="serial-command" placeholder="输入命令..." class="flex-1 bg-gray-700 border border-gray-600 rounded-lg py-2 px-3 text-white text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <button id="send-command" class="bg-gray-700 hover:bg-gray-600 text-white py-2 px-4 rounded-lg text-sm transition">发送</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 底部信息 -->
            <footer class="text-center text-gray-400 text-sm mt-8 pt-6 border-t border-gray-800">
                <p>ESP32 开发辅助工具 &copy; 2023 - 简化您的嵌入式开发流程</p>
            </footer>
        `;
    }

    // 渲染模态框容器
    renderModalContainer() {
        // 模态框已在HTML中定义，这里不需要重新渲染
    }

    // 绑定事件
    bindEvents() {
        // 芯片型号改变
        const chipSelect = document.getElementById('chipSelect');
        if (chipSelect) {
            chipSelect.addEventListener('change', (e) => {
                this.emit('chipChange', e.target.value);
            });
        }

        // 项目名称改变
        const projectNameInput = document.getElementById('projectName');
        if (projectNameInput) {
            projectNameInput.addEventListener('input', (e) => {
                this.emit('projectNameChange', e.target.value);
            });
        }

        // WiFi功能开关
        const wifiToggle = document.getElementById('wifiEnabled');
        if (wifiToggle) {
            wifiToggle.addEventListener('change', (e) => {
                const wifiConfig = document.getElementById('wifiConfig');
                if (wifiConfig) {
                    if (e.target.checked) {
                        wifiConfig.classList.remove('hidden');
                    } else {
                        wifiConfig.classList.add('hidden');
                    }
                }
                
                // 更新功能配置
                const features = {
                    wifi: e.target.checked,
                    mqtt: document.getElementById('mqttEnabled')?.checked || false,
                    ota: document.getElementById('otaEnabled')?.checked || false
                };
                this.emit('featureToggle', features);
            });
        }

        // MQTT功能开关
        const mqttToggle = document.getElementById('mqttEnabled');
        if (mqttToggle) {
            mqttToggle.addEventListener('change', (e) => {
                const features = {
                    wifi: document.getElementById('wifiEnabled')?.checked || false,
                    mqtt: e.target.checked,
                    ota: document.getElementById('otaEnabled')?.checked || false
                };
                this.emit('featureToggle', features);
            });
        }

        // OTA功能开关
        const otaToggle = document.getElementById('otaEnabled');
        if (otaToggle) {
            otaToggle.addEventListener('change', (e) => {
                const features = {
                    wifi: document.getElementById('wifiEnabled')?.checked || false,
                    mqtt: document.getElementById('mqttEnabled')?.checked || false,
                    ota: e.target.checked
                };
                this.emit('featureToggle', features);
            });
        }

        // LED引脚配置改变
        const ledPinInput = document.getElementById('ledPin');
        if (ledPinInput) {
            ledPinInput.addEventListener('change', (e) => {
                const pin = parseInt(e.target.value);
                if (!isNaN(pin)) {
                    this.emit('pinConfigChange', { type: 'led', pin });
                }
            });
        }

        // DHT11引脚配置改变
        const dht11PinInput = document.getElementById('dht11Pin');
        if (dht11PinInput) {
            dht11PinInput.addEventListener('change', (e) => {
                const pin = parseInt(e.target.value);
                if (!isNaN(pin)) {
                    this.emit('pinConfigChange', { type: 'dht11', pin });
                }
            });
        }

        // 重新生成代码
        const regenerateBtn = document.getElementById('regenerateCode');
        if (regenerateBtn) {
            regenerateBtn.addEventListener('click', () => {
                this.emit('generateCode');
            });
        }

        // 复制代码
        const copyCodeBtn = document.getElementById('copyCode');
        if (copyCodeBtn) {
            copyCodeBtn.addEventListener('click', () => {
                const codePreview = document.getElementById('codePreview');
                if (codePreview) {
                    const codeText = codePreview.textContent || codePreview.innerText;
                    navigator.clipboard.writeText(codeText)
                        .then(() => {
                            this.showAlert('代码已复制到剪贴板', 'success');
                        })
                        .catch(err => {
                            this.showAlert('复制失败: ' + err, 'error');
                        });
                }
            });
        }

        // 下载项目
        const downloadBtn = document.getElementById('downloadProject');
        if (downloadBtn) {
            downloadBtn.addEventListener('click', () => {
                this.emit('downloadProject');
            });
        }

        // 下载ESP项目
        const downloadESPBtn = document.getElementById('downloadESPProject');
        if (downloadESPBtn) {
            downloadESPBtn.addEventListener('click', () => {
                this.emit('downloadESPProject');
            });
        }

        // 导出Git
        const exportGitBtn = document.getElementById('exportGit');
        if (exportGitBtn) {
            exportGitBtn.addEventListener('click', () => {
                this.emit('exportGit');
            });
        }

        // 连接设备
        const connectBtn = document.getElementById('connectSerial');
        if (connectBtn) {
            connectBtn.addEventListener('click', () => {
                this.emit('connectDevice');
            });
        }

        // 烧录固件
        const flashBtn = document.getElementById('flashFirmware');
        if (flashBtn) {
            flashBtn.addEventListener('click', () => {
                this.emit('flashFirmware');
            });
        }

        // 连接WiFi
        const connectWifiBtn = document.getElementById('connectWifi');
        if (connectWifiBtn) {
            connectWifiBtn.addEventListener('click', () => {
                const ssid = document.getElementById('wifiName')?.value;
                const password = document.getElementById('wifiPass')?.value;
                if (ssid && password) {
                    this.emit('connectWifi', { ssid, password });
                } else {
                    this.showAlert('请输入WiFi名称和密码', 'error');
                }
            });
        }

        // 交互方式切换
        const interactionTabs = document.querySelectorAll('.interaction-tab');
        interactionTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // 更新激活状态
                interactionTabs.forEach(t => {
                    t.classList.remove('text-blue-400', 'border-blue-400', 'active');
                });
                tab.classList.add('text-blue-400', 'border-blue-400', 'active');

                // 显示对应面板
                const tabName = tab.getAttribute('data-tab');
                document.querySelectorAll('.interaction-content').forEach(panel => {
                    panel.classList.add('hidden');
                });
                
                const activePanel = document.getElementById(`${tabName}Panel`);
                if (activePanel) {
                    activePanel.classList.remove('hidden');
                }
            });
        });

        // 代码预览标签页切换
        setTimeout(() => {
            this.setupTabSwitching();
        }, 100);

        // 打开库管理器
        const openLibraryManagerBtn = document.getElementById('openLibraryManager');
        if (openLibraryManagerBtn) {
            openLibraryManagerBtn.addEventListener('click', () => {
                this.emit('openLibraryManager');
            });
        }

        // 关闭库管理器
        const closeLibraryManagerBtn = document.getElementById('closeLibraryManager');
        if (closeLibraryManagerBtn) {
            closeLibraryManagerBtn.addEventListener('click', () => {
                this.emit('closeLibraryManager');
            });
        }
    }

    // 更新引脚图
    updatePinDiagram() {
        const pinConfiguration = document.getElementById('pin-configuration');
        if (!pinConfiguration) return;

        const chipModel = this.state.getChipModel();
        const pinConfigurations = this.state.getPinConfigurations();

        // 定义各芯片型号的引脚数量和名称
        const chipPinInfo = {
            'esp32': {
                name: 'ESP32',
                image: 'src/assets/images/esp32.png',
                pins: 39, // 实际可用GPIO数量
                unavailable: [6, 7, 8, 9, 10, 11, 20, 24, 28, 29, 30, 31, 37, 38] // 通常不使用的引脚
            },
            'esp32-s2': {
                name: 'ESP32-S2',
                image: 'src/assets/images/esp32-s2.png',
                pins: 47,
                unavailable: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46]
            },
            'esp32-s3': {
                name: 'ESP32-S3',
                image: 'src/assets/images/esp32-s3.png',
                pins: 49,
                unavailable: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46]
            },
            'esp32-c3': {
                name: 'ESP32-C3',
                image: 'src/assets/images/esp32-c3.png',
                pins: 22,
                unavailable: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
            }
        };

        let pinDiagramHTML = '';

        if (chipPinInfo[chipModel]) {
            const chipInfo = chipPinInfo[chipModel];
            const availablePins = [];
            
            // 生成可用引脚列表
            for (let i = 0; i <= chipInfo.pins; i++) {
                if (!chipInfo.unavailable.includes(i)) {
                    availablePins.push(i);
                }
            }
            
            // 创建表格形式的引脚配置界面
            pinDiagramHTML = `
                <div class="text-center">
                    <h3 class="text-lg font-semibold mb-4">${chipInfo.name} 引脚配置</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-gray-800 rounded-lg">
                            <thead>
                                <tr>
                                    <th class="py-2 px-4 border-b border-gray-700">引脚</th>
                                    <th class="py-2 px-4 border-b border-gray-700">模式</th>
                                    <th class="py-2 px-4 border-b border-gray-700">描述</th>
                                    <th class="py-2 px-4 border-b border-gray-700">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${availablePins.map((pin, index) => {
                                    const pinConfig = pinConfigurations[pin] || {};
                                    return `
                                        <tr class="${index % 2 === 0 ? 'bg-gray-750' : 'bg-gray-800'} pin-row" data-pin="${pin}">
                                            <td class="py-2 px-4 border-b border-gray-700">GPIO${pin}</td>
                                            <td class="py-2 px-4 border-b border-gray-700">${pinConfig.mode || '未配置'}</td>
                                            <td class="py-2 px-4 border-b border-gray-700">${pinConfig.description || ''}</td>
                                            <td class="py-2 px-4 border-b border-gray-700">
                                                <button class="px-3 py-1 bg-blue-600 hover:bg-blue-700 rounded text-sm pin-config-btn" data-pin="${pin}">
                                                    配置
                                                </button>
                                            </td>
                                        </tr>
                                    `;
                                }).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        } else {
            // 如果没有匹配的芯片型号，显示选择提示
            pinDiagramHTML = `
                <div class="text-center py-8">
                    <div class="inline-block p-4 bg-gray-800 rounded-full mb-4">
                        <i class="fas fa-microchip text-3xl text-blue-400"></i>
                    </div>
                    <h3 class="text-xl font-semibold mb-2">请选择芯片型号</h3>
                    <p class="text-gray-400">从上方下拉菜单中选择您的ESP32芯片型号以开始配置引脚</p>
                </div>
            `;
        }

        pinConfiguration.innerHTML = pinDiagramHTML;

        // 为配置按钮添加点击事件
        const configButtons = pinConfiguration.querySelectorAll('.pin-config-btn');
        configButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                const pin = parseInt(e.currentTarget.getAttribute('data-pin'));
                this.openPinConfigModal(pin);
            });
        });
    }

    // 打开引脚配置模态框
    openPinConfigModal(pin) {
        this.currentPin = pin;
        
        // 创建或更新模态框
        let modal = document.getElementById('pin-config-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'pin-config-modal';
            modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 hidden';
            modal.innerHTML = `
                <div class="bg-gray-800 rounded-xl p-6 w-full max-w-md">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-xl font-bold">配置引脚 GPIO${pin}</h3>
                        <button id="close-pin-config" class="text-gray-400 hover:text-white">
                            <i class="fas fa-times text-2xl"></i>
                        </button>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2 text-gray-300">模式</label>
                        <select id="pin-mode" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="input">输入 (Input)</option>
                            <option value="output">输出 (Output)</option>
                            <option value="pwm">PWM 输出</option>
                            <option value="adc">ADC 输入</option>
                            <option value="dac">DAC 输出</option>
                            <option value="i2c">I2C 通信</option>
                            <option value="spi">SPI 通信</option>
                            <option value="uart">UART 通信</option>
                            <option value="ledc">LEDC (LED 控制)</option>
                            <option value="touch">触摸感应</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium mb-2 text-gray-300">描述</label>
                        <input type="text" id="pin-description" placeholder="引脚功能描述（可选）" 
                               class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div class="flex justify-end space-x-2">
                        <button id="cancel-pin-config" class="px-4 py-2 text-gray-400 hover:text-white transition">
                            取消
                        </button>
                        <button id="save-pin-config" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
                            保存
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // 绑定关闭事件
            document.getElementById('close-pin-config').addEventListener('click', () => {
                this.closePinConfigModal();
            });
            
            document.getElementById('cancel-pin-config').addEventListener('click', () => {
                this.closePinConfigModal();
            });
            
            document.getElementById('save-pin-config').addEventListener('click', () => {
                this.savePinConfiguration();
            });
        }

        // 更新当前引脚显示
        const modalTitle = modal.querySelector('h3');
        if (modalTitle) {
            modalTitle.textContent = `配置引脚 GPIO${pin}`;
        }
        
        // 设置当前引脚的配置值
        const pinModeSelect = document.getElementById('pin-mode');
        const pinDescriptionInput = document.getElementById('pin-description');
        const pinConfig = this.state.getPinConfigurations()[pin];
        
        if (pinModeSelect && pinConfig && pinConfig.mode) {
            pinModeSelect.value = pinConfig.mode;
        } else if (pinModeSelect) {
            pinModeSelect.value = 'output'; // 默认值为输出模式
        }
        
        if (pinDescriptionInput && pinConfig && pinConfig.description) {
            pinDescriptionInput.value = pinConfig.description;
        } else if (pinDescriptionInput) {
            pinDescriptionInput.value = ''; // 清空描述
        }

        // 显示模态框
        modal.classList.remove('hidden');
        
        // 阻止背景滚动
        document.body.style.overflow = 'hidden';
    }

    // 关闭引脚配置模态框
    closePinConfigModal() {
        const modal = document.getElementById('pin-config-modal');
        if (modal) {
            modal.classList.add('hidden');
        }
        this.currentPin = null;
        
        // 恢复背景滚动
        document.body.style.overflow = '';
    }

    // 保存引脚配置
    savePinConfiguration() {
        if (this.currentPin === null) return;
        
        const pinModeSelect = document.getElementById('pin-mode');
        const pinDescriptionInput = document.getElementById('pin-description');
        
        if (pinModeSelect) {
            const mode = pinModeSelect.value;
            const description = pinDescriptionInput ? pinDescriptionInput.value : '';
            
            // 保存配置
            this.emit('pinConfig', this.currentPin, { mode, description });
            
            // 关闭模态框
            this.closePinConfigModal();
        }
    }

    // 更新代码预览
    updateCodePreview(content) {
        const codePreview = document.getElementById('codePreview');
        if (codePreview) {
            // 清空内容并添加预格式化文本
            codePreview.innerHTML = '';
            const preElement = document.createElement('pre');
            preElement.className = 'm-0';
            const codeElement = document.createElement('code');
            codeElement.className = 'language-c';
            codeElement.textContent = content || '// 选择一个标签页查看代码';
            preElement.appendChild(codeElement);
            codePreview.appendChild(preElement);
            
            // 如果有highlight.js，则应用代码高亮
            if (window.hljs) {
                window.hljs.highlightElement(codeElement);
            }
        }
    }
    
    // 设置标签页切换功能
    setupTabSwitching() {
        const tabButtons = document.querySelectorAll('.tab-button');
        tabButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                // 更新激活状态
                tabButtons.forEach(b => {
                    b.classList.remove('text-blue-400', 'border-blue-400');
                    b.classList.add('text-gray-400');
                });
                btn.classList.remove('text-gray-400');
                btn.classList.add('text-blue-400', 'border-blue-400');

                // 根据标签更新代码预览内容
                const tabName = btn.getAttribute('data-tab');
                const files = this.state.getProjectFiles();
                
                let content = '// 选择一个标签页查看代码';
                switch(tabName) {
                    case 'main':
                        content = files['main/app_main.c'] || content;
                        break;
                    case 'config':
                        content = files['main/user_config.h'] || content;
                        break;
                    case 'gpio':
                        content = files['main/user_gpio.c'] || content;
                        break;
                    case 'wifi':
                        content = files['main/user_wifi.c'] || content;
                        break;
                    case 'mqtt':
                        content = files['main/user_mqtt.c'] || content;
                        break;
                    default:
                        content = `// ${tabName} 文件内容`;
                }
                
                this.updateCodePreview(content);
            });
        });
    }

    /**
     * 更新调试状态显示
     */
    updateDebugStatus(isDebugging) {
        const debugStatusEl = document.getElementById('debug-status');
        if (debugStatusEl) {
            if (isDebugging) {
                debugStatusEl.innerHTML = `
                    <p class="text-green-400">调试运行中</p>
                    <p class="mt-1">状态: <span class="text-yellow-400">等待断点</span></p>
                `;
            } else {
                debugStatusEl.innerHTML = '<p>调试未启动</p>';
            }
        }
    }

    /**
     * 更新断点列表显示
     */
    updateBreakpointsList(breakpoints) {
        const breakpointsListEl = document.getElementById('breakpoints-list');
        if (breakpointsListEl) {
            if (breakpoints && breakpoints.length > 0) {
                breakpointsListEl.innerHTML = breakpoints.map(bp => `
                    <div class="flex justify-between items-center py-1 border-b border-gray-700">
                        <span>${bp.fileName}:${bp.line}</span>
                        <button class="text-red-400 hover:text-red-300 text-xs" 
                                onclick="window.esp32DevTool.removeBreakpoint('${bp.fileName}', ${bp.line})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                `).join('');
            } else {
                breakpointsListEl.innerHTML = '<p>暂无断点</p>';
            }
        }
    }

    /**
     * 添加到串口监视器
     */
    appendToSerialMonitor(message, type = 'info') {
        const serialMonitor = document.getElementById('serial-monitor');
        if (serialMonitor) {
            const messageElement = document.createElement('p');
            
            // 根据消息类型设置样式
            switch(type) {
                case 'error':
                    messageElement.className = 'serial-error';
                    break;
                case 'success':
                    messageElement.className = 'serial-success';
                    break;
                case 'info':
                    messageElement.className = 'serial-info';
                    break;
                case 'debug':
                    messageElement.className = 'serial-debug';
                    break;
                default:
                    messageElement.className = 'serial-message';
            }
            
            messageElement.textContent = message;
            serialMonitor.appendChild(messageElement);
            
            // 滚动到底部
            serialMonitor.scrollTop = serialMonitor.scrollHeight;
        }
    }

    // 显示提示信息
    showAlert(message, type = 'info') {
        // 创建提示框元素
        const alert = document.createElement('div');
        alert.className = `fixed top-4 right-4 z-50 px-4 py-2 rounded-lg shadow-lg transform transition-transform duration-300 ${
            type === 'success' ? 'bg-green-600' : 
            type === 'error' ? 'bg-red-600' : 
            type === 'warning' ? 'bg-yellow-600' : 'bg-blue-600'
        } text-white`;
        alert.innerHTML = `
            <div class="flex items-center">
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 
                                 type === 'error' ? 'fa-exclamation-circle' : 
                                 type === 'warning' ? 'fa-exclamation-triangle' : 'fa-info-circle'} mr-2"></i>
                <span>${message}</span>
                <button class="ml-4 text-white hover:text-gray-200">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;

        // 添加到文档中
        document.body.appendChild(alert);

        // 添加关闭事件
        const closeBtn = alert.querySelector('button');
        closeBtn.addEventListener('click', () => {
            alert.remove();
        });

        // 3秒后自动移除
        setTimeout(() => {
            if (alert.parentNode) {
                alert.remove();
            }
        }, 3000);
    }

    // 加载配置
    loadConfig(config) {
        // 加载芯片型号
        const chipSelect = document.getElementById('chipSelect');
        if (chipSelect && config.chipModel) {
            chipSelect.value = config.chipModel;
        }

        // 加载项目名称
        const projectNameInput = document.getElementById('projectName');
        if (projectNameInput && config.projectName) {
            projectNameInput.value = config.projectName;
        }

        // 加载功能开关
        if (config.features) {
            Object.keys(config.features).forEach(feature => {
                const element = document.getElementById(`${feature}Enabled`);
                if (element) {
                    element.checked = config.features[feature];
                }
            });
            
            // 根据WiFi开关状态更新WiFi配置区域显示
            const wifiConfig = document.getElementById('wifiConfig');
            if (wifiConfig) {
                if (config.features.wifi) {
                    wifiConfig.classList.remove('hidden');
                } else {
                    wifiConfig.classList.add('hidden');
                }
            }
        }

        // 加载引脚配置
        if (config.ledPin !== undefined) {
            const ledPinInput = document.getElementById('ledPin');
            if (ledPinInput) {
                ledPinInput.value = config.ledPin;
            }
        }

        if (config.dht11Pin !== undefined) {
            const dht11PinInput = document.getElementById('dht11Pin');
            if (dht11PinInput) {
                dht11PinInput.value = config.dht11Pin;
            }
        }

        // 更新引脚图
        this.updatePinDiagram();
    }

    // 事件发射器
    emit(event, data) {
        if (this.events[event]) {
            this.events[event].forEach(callback => callback(data));
        }
    }

    // 事件监听器
    on(event, callback) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
    }

    // 工具函数：转义HTML
    escapeHtml(unsafe) {
        return unsafe
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
    }

    // 更新文件结构显示
    updateFileStructureDisplay() {
        const fileStructure = document.getElementById('file-structure');
        if (!fileStructure) return;

        const files = this.state.getProjectFiles();
        const projectName = this.state.getProjectName();
        const features = this.state.getFeatures();

        if (Object.keys(files).length === 0) {
            fileStructure.innerHTML = '<p class="text-gray-400 text-center">生成代码后将显示项目文件结构</p>';
            return;
        }

        let structureHtml = `
        <div class="tree text-gray-300">
            <ul>
                <li>${projectName}/
                    <ul>
                        <li><i class="fas fa-file-alt text-blue-400 mr-1"></i> CMakeLists.txt</li>
                        <li><i class="fas fa-file-alt text-blue-400 mr-1"></i> sdkconfig</li>
        `;

        if (features.ota) {
            structureHtml += `<li><i class="fas fa-file-alt text-blue-400 mr-1"></i> partitions.csv</li>`;
        }

        structureHtml += `
                        <li class="mt-1">main/
                            <ul>
                                <li><i class="fas fa-file-code text-green-400 mr-1"></i> main.c</li>
                            </ul>
                        </li>
        `;

        // 检查是否有特殊组件
        const pinConfigs = this.state.getPinConfigurations();
        let hasSpecialComponents = false;
        for (const pin in pinConfigs) {
            const config = pinConfigs[pin];
            if (['pwm', 'adc', 'uart', 'i2c', 'spi'].includes(config.mode)) {
                hasSpecialComponents = true;
                break;
            }
        }

        if (hasSpecialComponents || features.httpServer || features.ota) {
            structureHtml += `
                        <li class="mt-1">components/
                            <ul>
                                <li><i class="fas fa-folder text-yellow-400 mr-1"></i> ...</li>
                            </ul>
                        </li>
            `;
        }

        structureHtml += `
                    </ul>
                </li>
            </ul>
        </div>`;

        fileStructure.innerHTML = structureHtml;
    }
}